//Copyright (c) 2006-2007 Microsoft Corporation.  All rights reserved
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace InvocationFramework.Common.Library
{
    /// <summary>
    /// Helper para serializar objetos a Xml
    /// </summary>
    internal static class XmlSerializerHelper
    {
        #region Public Methods

        /// <summary>
        /// Serializa un objeto a Xml
        /// </summary>
        /// <param name="obj">Objeto a serializar</param>
        /// <returns>Xml del objeto serializado</returns>
        public static string SerializeToXml( object obj )
        {
            XmlTextReader xtr = null;
            try
            {
                XmlSerializer xs = new XmlSerializer( obj.GetType( ) );
                using ( MemoryStream ms = new MemoryStream( ) )
                {
                    XmlTextWriter w = new XmlTextWriter( ms, Encoding.UTF8 );
                    w.Formatting = System.Xml.Formatting.None;
                    xs.Serialize( w, obj );
                    w.Flush( );
                    
                    return Encoding.UTF8.GetString( ms.ToArray( ) ).Remove( 0, 1 );
                }
            }
            finally
            {
                if ( xtr != null ) xtr.Close( );
            }
        }

        /// <summary>
        /// Crea un objeto a partir de un Xml
        /// </summary>
        /// <param name="xml">Xml del objeto serializado</param>
        /// <param name="type">Tipo del objeto a crear</param>
        /// <returns>El objeto deserializado</returns>
        public static object DeserializeFromXml( string xml, Type type )
        {
            using ( StringReader sr = new StringReader( xml ) )
            {
                XmlSerializer xs = new XmlSerializer( type );
                
                return xs.Deserialize( sr );
            }
        }

        #endregion
    } 
}